import java.lang.reflect.Field;

public class SimpleMapper {
    public static String toString(Object obj) {
        StringBuilder sb = new StringBuilder();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        sb.append(clazz.getName()).append(" [");
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object fieldValue = null;
            try {
                fieldValue = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            sb.append(fieldName).append("=").append(fieldValue).append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        sb.append("]");

        return sb.toString();
    }

    public static Object fromString(String str) {
        int startIndex = str.indexOf("[");
        int endIndex = str.lastIndexOf("]");
        String className = str.substring(0, startIndex).trim();//去除
        String fieldString = str.substring(startIndex + 1, endIndex);

        try {
            Class<?> clazz = Class.forName(className);
            Object obj = clazz.getDeclaredConstructor().newInstance();

            String[] fields = fieldString.split(", ");
            for (String field : fields) {
                String[] parts = field.split("=");
                String fieldName = parts[0].trim();
                String fieldValue = parts[1].trim();

                Field declaredField = clazz.getDeclaredField(fieldName);
                declaredField.setAccessible(true);

                if (declaredField.getType() == int.class) {
                    declaredField.setInt(obj, Integer.parseInt(fieldValue));
                } else {
                    declaredField.set(obj, fieldValue);
                }
            }

            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        Person p1 = new Person("Lucky", 18, "female");
        String str = SimpleMapper.toString(p1);
        Person p2 = (Person) SimpleMapper.fromString(str);
        System.out.println(p2);
    }
}

class Person {
    String name;
    int age;
    String sex;

    public Person() {
    }

    public Person(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }
}